package com.ykdl.app.Utils;

import org.apache.http.HttpHost;

import android.content.Context;
import android.database.Cursor;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Proxy;
import android.net.Uri;
import android.net.wifi.WifiManager;

import com.ykdl.app.common.MyApplication;
/**
 * 判断网络的工具类
 */
public class ApnUtil {

	private static Uri PREFERRED_APN_URI = Uri

	.parse("content://telephony/carriers/preferapn");

	public static String getApnType(Context context) {
		String apntype = APN.WIFI;
		try{
		Cursor c = context.getContentResolver().query(PREFERRED_APN_URI, null,
				null, null, null);
		if(c.moveToFirst()){
		int index=c.getColumnIndex("proxy");
		if(index!=-1){
		String user = c.getString(index);
		if (isWifi(context)){
			apntype = APN.WIFI;			
		}else if(user!=null&&(user.equals(APN.CMPROXY)||user.equals(APN.CTPROXY))) {
			apntype = APN.WAP;
		} else {
			apntype = APN.NET;
		}
		}
		}
	    c.close();
	    }catch(Exception ee){
	    	
	    }
		return apntype;

	}
	public static boolean isWifi(Context context){
		WifiManager wm = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);  
	    return wm.getWifiState()==WifiManager.WIFI_STATE_ENABLED;
	
	}
	
	
	/**
	 * 获得代理服务器
	 * @return
	 */
	public static HttpHost  getHttpHost(){
		ConnectivityManager  cm = (ConnectivityManager) MyApplication.getInstance().getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo   info =  cm.getActiveNetworkInfo();
		HttpHost   host = null;
		if(null== info)return null;
		
	      if(info.getType() == ConnectivityManager.TYPE_MOBILE){
	    	  //代理服务器
	    	  String  proxyHost = Proxy.getHost(MyApplication.getInstance().getApplicationContext());
	    	  if(null == proxyHost){
	    		  proxyHost = Proxy.getDefaultHost();
	    	  }
	    	  //端口号
	    	  int  port = Proxy.getPort(MyApplication.getInstance().getApplicationContext());
	    	  
	    	  if(port == -1){
	    		  port = Proxy.getDefaultPort();
	    	  }
	    	  if(proxyHost != null && port > -1){
	    		   host = new HttpHost(proxyHost, port);
	    	  }else{
	    		 return host;
	    	  }
	      }
	    return host;
	}
	
	public static boolean isActivityApnConnected(Context context) {
        boolean isConnected = false;
        ConnectivityManager conMgr = (ConnectivityManager)(context.getSystemService(Context.CONNECTIVITY_SERVICE));
        NetworkInfo info = conMgr.getActiveNetworkInfo();
        if (null != info) {
            isConnected = info.isConnected();
        }
        return isConnected;
    }
	
	
	
}
